#!/usr/bin/python
# -*- coding: utf-8  -*-
"""
Based on the basic.py script.
 
"""
import wikipedia
import pagegenerators
import sys
import re
 
summary = u"Bot: Creando redirección hacia "
 
try:
    start = list()
    test = False
    for arg in wikipedia.handleArgs():
        if arg.startswith("-test"):
            test = True
        else:
            start.append(arg)
    if start:
        start = " ".join(start)
    else:
        start = u"!"
    mysite = wikipedia.getSite()
    # If anything needs to be prepared, you can do it here
    basicgenerator = pagegenerators.AllpagesPageGenerator(start=start)
    generator = pagegenerators.PreloadingGenerator(basicgenerator)
 
    for page in generator:
        # skip redirects
        if page.isRedirectPage():
            continue
 
        pagetitle = page.title()
        # condition for pages
        if pagetitle.find("-")  > 0:            
            # new titles
            newtitles     = pagetitle.split(' - ')
            suggestions   = [">>> %s <<<" % x for x in newtitles]
            newredirects  = [wikipedia.Page(mysite, title) for title in newtitles ]         
            allexist = 1           
            for x in newredirects:
                allexist = allexist and x.exists()   
 
            if allexist:
                # all needed redirects exist; print a message and skip to the next page
                wikipedia.output(u'>>>> \03{lightpurple}%s\03{default} <<<< -- redirects already exist, skipping\n' % pagetitle)
                continue
 
            wikipedia.output(u'\n>>>> \03{lightpurple}%s\03{default} <<<<' % pagetitle)
            wikipedia.output(u'\03{lightyellow}Redirecciones sugeridas:\03{default} %s ' % ', '.join(suggestions) )     
            ask = wikipedia.input(u'¿Qué hacemos: (c)rear redirecciones, siguiente pági[n]a, (s)alir?')                
            if ask in ['c', 'C']:
                for x in newredirects:
                    # for each new title split from the current page, create a redirect
                    if x.exists():
                      print u"La página [[%s]] ya existe" % x.title()
                    else:
                      content  = '#REDIRECT [[%s]]' % pagetitle
                      print u"    La redirección será: " + content                  
                      x.put(content, comment = summary + u'[[' + pagetitle + u']]')
 
 
            elif ask in ['n', 'N']:
                pass
            elif ask in ['s', 'S']:
                sys.exit()
            else:
                wikipedia.output(u'Entrada incorrecta')
                self.run()                                
finally:
    wikipedia.stopme()
